package org.wtframework.platform.web.mvc.action.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.openredhead.springx.core.server.service.FilePaths;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.wtframework.platform.server.model.impl.FileMeta;
import org.wtframework.platform.server.model.impl.ImageScale;
import org.wtframework.platform.server.service.FileMetaService;

import com.google.common.base.Strings;


/**
 * 
 * @author XueJingQue UploadFile Demo
 *
 */
@Controller
public class PbUploadFileController {

	private String PUBLICSHAREUPLOAD = "jsp/share/pb-upload";

	private String PUBLICSHAREuploadify = "demo/pb-uploadify";
	
	@Resource private FileMetaService fileMetaService;
	
	@RequestMapping("/pb-upload-ui")
	public String doUploadFileUi() throws Exception {
		
		return PUBLICSHAREUPLOAD;
		
	}
	@RequestMapping("/pb-uploadify-ui")
	public String douploadifyUi() throws Exception {
		
		return PUBLICSHAREuploadify;
		
	}

	
	
	
	@RequestMapping(value="/pb-upload-json", method = RequestMethod.POST)
	@ResponseBody
	public Object doUploadFilePost(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
	
		
		//System.out.println(request.);
		
		LinkedList<FileMeta> files = new LinkedList<FileMeta>();
		
		FileMeta fileMeta = null;
		
		Iterator<String> itr = request.getFileNames();
		
		MultipartFile mpf = null;
		
		String filePath = FilePaths.getExposeTemporaryPath();
		
		String targetFile = "";
		 while(itr.hasNext()){
			 
             // get next MultipartFile
             mpf = request.getFile(itr.next()); 

 
             //if files > 10 remove the first from the list
             if(files.size() >= 10)
                 files.pop();
 
             //create new fileMeta
             fileMeta = new FileMeta();
             
             fileMeta.setFileName(mpf.getOriginalFilename());
             
             //fileMeta.setFileSize(mpf.getSize()/1024+" Kb");
             fileMeta.setFileSize(mpf.getSize()+"");
             
             fileMeta.setFileType(getFileType(mpf.getOriginalFilename()));

             targetFile = filePath+File.separator+UUID.randomUUID()+"."+getFileType(mpf.getOriginalFilename());
             
             fileMeta.setFileUrl(targetFile.replace(FilePaths.getSystemRootPath(), ""));

             try {
            	 
                 FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(targetFile));
                 String width = request.getParameter("width");
                 if(!Strings.isNullOrEmpty(width)){
                	 ImageScale.resize(new File(targetFile), new File(targetFile), Integer.parseInt(width), 1f);
                 }
                 fileMetaService.saveFile(fileMeta);
                 
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             //2.4 add to files
             files.add(fileMeta);
         }

		if("text/*".equals(request.getHeader("Accept"))){
			String result = "{'fileName':'"+fileMeta.getFileName()+"','fileUrl':'"+fileMeta.getFileUrl().replace("\\", "/")
	    	+"','fileId':'"+fileMeta.getId()+"','fileSize':'"+fileMeta.getFileSize()+"'}";
			return result;
		}
		else if("*/*".equals(request.getHeader("Accept"))){
			
			return fileMeta;
		}

        return fileMeta;
	}
	
	private String getFileType(String originalFilename) {
		// TODO Auto-generated method stub
		return originalFilename.substring(originalFilename.lastIndexOf('.')+1).toLowerCase();
	}
}
